#include "stdafx.h"
#include "Logger.h"

#include "Poco/Message.h"
#include "Poco/PatternFormatter.h"
#include "Poco/FormattingChannel.h"
#include "Poco/ConsoleChannel.h"
#include "Poco/SplitterChannel.h"
#include "Poco/FileChannel.h"
#include "Poco/StreamChannel.h"
#include "Poco/UnicodeConverter.h"

#include <fstream>
#include <iostream>
#include <fcntl.h>
#include <io.h>

namespace ExamSystem
{
    using Poco::PatternFormatter;
    using Poco::FormattingChannel;
    using Poco::ConsoleChannel;
    using Poco::SplitterChannel;
    using Poco::Message;
    using Poco::FileChannel;
    using Poco::StreamChannel;

    Logger *CExamLogger::ms_systemLogger = NULL;
    AutoPtr<Channel> CExamLogger::ms_splitterChannel;
    AutoPtr<Channel> CExamLogger::ms_consoleChannel;
    AutoPtr<Channel> CExamLogger::ms_fileChannel;
    AutoPtr<Formatter> CExamLogger::ms_formatter;
    AutoPtr<Channel> CExamLogger::ms_formattingChannel;

    CExamLogger::CExamLogger(void)
    {
    }

    Logger & CExamLogger::SystemLogger(void)
    {
        return *ms_systemLogger;
    }

    Logger & CExamLogger::CreateLogger(const char *fileName, Poco::Message::Priority prio)
    {
        if (NULL == ms_systemLogger)
        {
            ms_splitterChannel = new SplitterChannel();

            //ms_consoleChannel = new ConsoleChannel();
            ms_consoleChannel = new StreamChannel(std::cout);
            static_cast<SplitterChannel *>(ms_splitterChannel.get())->addChannel(ms_consoleChannel);

            // check if the file could be open
            std::ofstream fout(fileName, std::ios::app | std::ios::out);
            if (fout.is_open())
            {
                fout.close();
                ms_fileChannel = new FileChannel(fileName);
                static_cast<SplitterChannel *>(ms_splitterChannel.get())->addChannel(ms_fileChannel);
            }

            ms_formatter = new PatternFormatter("%Y-%m-%d %H:%M:%S.%i: [%p] %t");
            ms_formatter->setProperty("times", "local");
            ms_formattingChannel = new FormattingChannel(ms_formatter, ms_splitterChannel);

            ms_systemLogger = &Logger::create("SystemLog", ms_formattingChannel, prio);
        }

        return *ms_systemLogger;
    }

}